<template>
  <div class="page-box-height">
    <div v-if="!addFormVisible" class="page-container" v-loading="tableLoading">
      <div class="btns-line">
        <el-button type="primary" icon="el-icon-plus" @click="showAddForm('add')">新增表单</el-button>
      </div>
      <div v-if="tableOptions.tableData && tableOptions.tableData.length > 0" class="list-box flex flex-1">
        <form-item v-for="(item, index) in tableOptions.tableData" :key="item.formName + index" :item="item" @operation="operationItem"></form-item>
      </div>
      <div v-else class="list-box no-data">
        暂无数据
      </div>
      <footer class="text-right">
        <el-pagination class="page page-small" small @current-change="handleCurrentChange" :current-page="params.page" :page-size="params.size" layout="total, prev, pager, next" :total="params.total">
        </el-pagination>
      </footer>
    </div>
    <div v-else class="page-container">
      <div class="btns-line">
        <div class="fl">
          <span>
            {{ addFormTitle }}
          </span>
          <span class="equipment-icon-box">
            终端：
            <svg-icon class="equipment-icon" :class="{active: designDeviceChoose == 'PC'}" icon-class="pc" title="PC" @click.native="designDeviceClick('PC')"></svg-icon>
            <svg-icon class="equipment-icon" :class="{active: designDeviceChoose == 'APP'}" icon-class="APP" title="APP" @click.native="designDeviceClick('APP')"></svg-icon>
          </span>
        </div>
        <el-button type="primary" @click="preview">预览</el-button>
        <el-button type="primary" @click="subForm">保存</el-button>
        <el-button @click="hideAddForm">返回</el-button>
      </div>
      <div v-if="showGuide" class="flex-1 guide-box">
        <div class="btns-box">
          <span class="guide-btn" @click="guideBtnClick('no')">不再提示</span>
          <span class="guide-btn" @click="guideBtnClick('next')">下一步</span>
        </div>
        <img :src="guideImgs[guideIndex]" />
      </div>
      <operate-page-main v-else-if="operatePageMainShow" :initTemplateInfo.sync="initTemplateInfo[designDeviceChoose]" :treeInitTemplateInfo.sync="initTemplateInfo[designDeviceChoose]" :quickCreatePage="quickCreatePage"
        :designDeviceChoose="designDeviceChoose" :commonPageConfig="initTemplateInfo.commonPageConfig" ref="operateTemplate">
      </operate-page-main>
    </div>
  </div>
</template>

<script>
import operatePageMain from "./pageComponents/components/operatePageMain";
import FormItem from "./components/FormItem";
import { confirm } from "@/utils/tools";
import { getFormList, getSimpleFormList, setFormItem, delFormItem } from "@/api/formApi";

export default {
  name: "formManager",
  components: { operatePageMain, FormItem },
  data() {
    return {
      showGuide: true,
      guideImgs: [
        require("../../icons/png/guide1.png"),
        require("../../icons/png/guide2.png"),
        require("../../icons/png/guide3.png"),
        require("../../icons/png/guide4.png"),
        require("../../icons/png/guide5.png")
      ],
      designDeviceChoose: 'PC',
      guideIndex: 0,
      params: {
        page: 1,
        size: window.env.formPageSize,
        total: 0
      },
      searchData: {
        factoryId: window.localStorage.factoryId
      },
      tableOptions: {
        tableData: [],
        modifySettings: [
          {
            eventName: "modifyItem",
            name: "编辑",
            btnType: "",
            code: "mes-systemConfig-manage-btn_edit"
          },
          {
            eventName: "deleteItem",
            name: "删除",
            btnType: "danger",
            code: "mes-systemConfig-manage-btn_delete"
          }
        ],
        _columns: [
          {
            prop: "formName",
            label: "表单名称"
          },
          {
            prop: "formTypeId",
            label: "表单类型"
          },
          {
            prop: "description",
            label: "表单描述"
          }
        ]
      },
      tableLoading: false,
      addFormVisible: false,
      addFormTitle: "新建表单",
      initTemplateInfo: {
        APP: {
          sortable: [{ name: 'design-tab0', ref: 'designTab', label: '首页', properties: {}, list: [] }],
          globalCss: {
            customTheme: true
          },
          pageEvent: {}
        },
        PC: {
          sortable: [{ name: 'design-tab0', ref: 'designTab', label: '首页', properties: {}, list: [] }],
          globalCss: {
            customTheme: true
          },
          pageEvent: {}
        },
        commonPageConfig: {
          templateName: '模板表单',
          moduleId: ""
        }
      },
      quickCreatePage: false, // 左边有树，快速创建
      operatePageMainShow: true,
      editItem: null,
    };
  },
  created() {
    this.getFormList();
  },
  computed: {
    factoryId() {
      return window.localStorage.factoryId;
    }
  },
  methods: {
    designDeviceClick(equipment) {
      this.designDeviceChoose = equipment
      this.operatePageMainShow = false
      this.$nextTick(() => {
        this.operatePageMainShow = true
      })
    },
    guideBtnClick(type) {
      if (type === "no") {
        this.showGuide = false;
        window.localStorage.setItem("hideGuide", true);
      } else {
        this.guideIndex === 4 ? (this.showGuide = false) : this.guideIndex++;
      }
    },
    getFormList() {
      this.tableLoading = true;
      getSimpleFormList(this.params, this.searchData).then(res => {
        this.tableLoading = false;
        if (!res.data) return;
        this.params.total = res.data.total;
        this.tableOptions.tableData = res.data.rows;
      }).catch(err => {
        this.tableLoading = false
      })
    },
    handleCurrentChange(val) {
      this.params.page = val;
      this.getFormList();
    },
    showAddForm(type) {
      if (type === "add") {
        this.isEdit = false;
        this.addFormTitle = "新建表单";
      } else {
        this.isEdit = true;
        this.addFormTitle = "编辑表单";
      }
      this.addFormVisible = true;
      this.showGuide = window.localStorage.hideGuide ? false : true;
      this.guideIndex = 0;
    },
    hideAddForm() {
      this.addFormVisible = false;
      this.PC = {
        sortable: [
          {
            name: "design-tab0",
            ref: "designTab",
            label: "首页",
            properties: {},
            list: []
          }
        ],
        globalCss: {
          customTheme: true
        },
        pageEvent: {}
      };
      this.initTemplateInfo = {
        APP: {
          sortable: [{ name: 'design-tab0', ref: 'designTab', label: '首页', properties: {}, list: [] }],
          globalCss: {
            customTheme: true
          },
          pageEvent: {}
        },
        PC: {
          sortable: [{ name: 'design-tab0', ref: 'designTab', label: '首页', properties: {}, list: [] }],
          globalCss: {
            customTheme: true
          },
          pageEvent: {}
        },
        commonPageConfig: {
          templateName: '模板表单',
          moduleId: ""
        }
      }
      this.getFormList();
    },
    preview() {
      localStorage.setItem("initTemplateInfo", JSON.stringify(this.initTemplateInfo));
      window.open("/preview");
    },
    subForm() {
      if (!this.initTemplateInfo.commonPageConfig.templateName) {
        this.$message.error("表单名称不能为空");
        return false;
      }

      let form = {
        factoryId: window.localStorage.factoryId,
        formContent: JSON.stringify(this.initTemplateInfo),
        formIcon: this.initTemplateInfo.commonPageConfig.pageImg,
        description: this.initTemplateInfo.commonPageConfig.descript,
        formName: this.initTemplateInfo.commonPageConfig.templateName,
        formTypeId: this.initTemplateInfo.commonPageConfig.formTypeId
      }

      if (this.isEdit) {
        form.formId = this.editItem.formId
      }

      setFormItem(form).then(res => {
        this.hideAddForm();
      });
    },
    // modifyItem(item) {
    //   this.showAddForm("edit");
    //   this.createForm = item.row;
    // },
    deleteItem(item) {
      delFormItem(item.row.formId).then(res => {
        this.$message({
          message: "删除表单成功",
          type: "success"
        });
        this.getFormList();
      });
    },
    operationItem(item) {
      if (item.type === 1) {
        // this.initTemplateInfo.commonPageConfig = {
        //   pageImg: item.formIcon,
        //   descript: item.description,
        //   templateName: item.formName,
        //   formTypeId: item.formTypeId,
        //   formId: item.formId
        // };
        console.log(item)
        let params = {
          page:1, size: 1
        }
        let data = {
          formId: item.formId,
          factoryId: window.localStorage.factoryId
        }
        this.tableLoading = true
        getFormList(params, data).then(res => {
          this.tableLoading = false
          if (res.data.rows && res.data.rows.length) {
            let formContent = res.data.rows[0].formContent
            try {
              this.initTemplateInfo = JSON.parse(formContent);
            } catch {
              console.error('解析 formContent 失败---- formContent: ', formContent);
            }
            this.editItem = res.data.rows[0]
            this.showAddForm("edit");
          }
        }).catch(e => {
          this.tableLoading = false
        })
      } else {
        confirm("删除之后不可撤销，是否确定？").then(res => {
          delFormItem({ formId: item.formId }).then(res => {
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.getFormList();
          });
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page-box-height {
  height: 100%;
}
.page-container {
  background: #fff;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .equipment-icon-box {
    display: inline-block;
    margin-left: 10px;
    color: #999;
    font-weight: 400;

    &::before {
      content: '';
      display: inline-block;
      height: 20px;
      border-left: 2px solid #ccc;
      margin-right: 10px;
      transform: translateY(3px);
    }

    .equipment-icon {
      margin-right: 8px;
      cursor: pointer;

      &.active {
        color: #477fe3;
      }
    }
  }

  .list-box {
    flex-wrap: wrap;
    overflow-y: auto;
    align-content: flex-start;

    &.no-data {
      text-align: center;
      font-size: 14px;
      font-weight: 700;
      line-height: 6em;
    }
  }

  .making-form-box {
    flex: 1;

    .form {
      border: 1px solid #ddd;
      width: 500px;
      margin: 20px auto;
      padding: 20px;
      padding-bottom: 2px;
    }
  }

  .guide-box {
    overflow: hidden;
    position: relative;

    .btns-box {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 10;

      .guide-btn {
        -webkit-user-select: none;
        user-select: none;
        color: #eaeaea;
        border: 1px solid #eaeaea;
        display: inline-block;
        padding: 8px 10px;
        margin-right: 10px;
        font-size: 18px;
        box-shadow: 2px 2px 2px 0 rgba(233, 233, 233, 0.6);
        cursor: pointer;

        &:hover {
          color: #fff;
          border-color: #fff;
        }
      }
    }
  }

  .footer {
    height: 80px;
  }
}
</style>

<style>
.making-form-box .fm2-container .el-footer {
  display: none;
}
</style>
